<template>
  <div class="login">
    <MyHead title="登录">
      <MyBack></MyBack>
    </MyHead>
    <div class="form">
      <van-form @submit="onSubmit" @failed="onFailed">
        <van-cell-group inset>
          <van-field
            v-model="form.mobile"
            required
            center
            clearable
            name="mobile"
            placeholder="请输入手机号码"
            :rules="[
              { required: true, message: '请填写手机号' },
              { pattern: reg.phone, message: '请输入正确的手机号' },
            ]"
          />

          <van-field
            v-model="form.captchaCode"
            required
            center
            clearable
            name="captchaCode"
            placeholder="请输入图形验证码"
            :rules="[
              { required: true, message: '请填写图形验证码' },
              { pattern: reg.imgCode, message: '请输入四位图形验证码' },
            ]"
          >
            <template #button>
              <img
                @click="toGetCaptchaImage"
                class="captcha_image"
                :src="obj.image"
                alt=""
              />
            </template>
          </van-field>

          <van-field
            v-model="form.smsCode"
            required
            center
            clearable
            name="smsCode"
            placeholder="请输入手机验证码"
            :rules="[
              { required: true, message: '请填写手机验证码' },
              { pattern: reg.pay, message: '请输入6位验证码' },
            ]"
          >
            <template #button>
              <van-button
                v-if="obj.flag"
                @click="startSendCaptcha"
                :disabled="disabled"
                size="small"
                type="primary"
                >获取验证码</van-button
              >
              <van-button v-else :disabled="true" size="small" type="default"
                >剩余 {{ count }} S</van-button
              >
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px">
          <van-button round block type="success" native-type="submit">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, computed } from "vue";
import MyBack from "../../components/MyBack.vue";
import { getPicCode, getMsgCode, codeLogin } from "../../api/api";
import { reg } from "../../utils/validate";
import { ShowError, ShowMsg, ShowSuccess } from "../../utils/message";
import { useIntervalFn, useCounter } from "@vueuse/core";
import { useCommon } from "../../hooks/common";
import VueCookies from "vue-cookies";
import { useUserStore } from "../../store/user";

const { todosetToken } = useUserStore();

const { gotopage } = useCommon();
const obj = reactive({
  image: "",
  key: "",
  flag: true,
  count: 18,
});

const { count, inc, dec, set, reset } = useCounter(180, { min: 0, max: 180 });
const { pause, resume } = useIntervalFn(
  () => {
    if (count.value > 0) {
      dec(1);
    } else {
      obj.flag = true;
      pause();
      reset();
    }
  },
  1000,
  {
    immediate: false,
  }
);

const form = reactive<any>({});
const disabled = computed(
  () => !(reg.phone.test(form.mobile) && reg.imgCode.test(form.captchaCode))
);

const startSendCaptcha = async () => {
  let res: any = await getMsgCode({
    form: {
      mobile: form.mobile,
      captchaCode: form.captchaCode,
      captchaKey: obj.key,
    },
  });
  if (res.status == 200) {
    ShowMsg(res.message);
    obj.flag = false;
    resume(); // 启动计时器
  } else {
    ShowMsg(res.message);
  }
};

const toGetCaptchaImage = async () => {
  let res: any = await getPicCode();
  if (res.status == 200) {
    obj.image = res.data.base64;
    obj.key = res.data.key;
  }
};
const onSubmit = async (value: any) => {
  console.log(value);
  let res: any = await codeLogin({
    form: {
      isParty: false,
      partyData: {},
      mobile: value.mobile,
      smsCode: value.smsCode,
    },
  });
  if (res.status == 200) {
    ShowSuccess("登录成功");
    gotopage("/shop/mine");
    VueCookies.set("LoginMobile", value.mobile, 30 * 24 * 60 * 60);
    todosetToken(res.data);
  }
};
const onFailed = () => {
  ShowError("登录数据校验失败");
};
onMounted(() => {
  toGetCaptchaImage();
  if (VueCookies.get("LoginMobile")) {
    form.mobile = VueCookies.get("LoginMobile");
  }
});
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;

  .form {
    height: 100%;
    margin-top: 50px;

    .captcha_image {
      width: 90px;
      height: 30px;
    }
  }
}
</style>